package net.sppan.blog.controller.admin;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.UeditorConfigKit;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import net.sppan.blog.annotation.RequiresPermissions;
import net.sppan.blog.commons.Constants;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.model.Role;
import net.sppan.blog.model.User;
import net.sppan.blog.model.UserRole;
import net.sppan.blog.utils.Const;
import net.sppan.blog.utils.ObjectUtils;
import net.sppan.blog.utils.WebUtils;
import net.sppan.blog.vo.UserVo;
import sun.misc.BASE64Decoder;

import java.util.Date;
import java.util.List;

@RequiresPermissions(key = { "admin:sys:user" })
public class AdminUserController extends BaseController {
	/**
	 * 用户列表
	 */
	@RequiresPermissions(key = { "admin:sys:user:list" })
	public void list() {
		String searchName = getPara("search_name");
		Integer searchRole = getParaToInt("search_role");
		String searchDate = getPara("search_date");
		String parentAgent = getPara("parent_agent");
		int pageNumber = getParaToInt("pageNumber", 1);
		int pageSize = getParaToInt("pageSize", 10);
		User currentUser = WebUtils.currentUser(getRequest(), getResponse());
		UserRole userRole = UserRole.dao.findFirstByUserId(currentUser.getId());
		String select = "select u.*,su.name as parent_name,r.name as role_name ";
		String sql = "from sys_user u left join sys_user su on u.parent=su.id join sys_user_role ur on u.id=ur.user_id join sys_role r on r.id=ur.role_id where 1=1";
		//代理只能查看属于他自己的子账号
		if (userRole.getRoleId().intValue() == Const.AgentId) {
			sql = sql + " and u.parent=" + currentUser.getId();
		} else {
			List<User> agents = User.dao.findUserByRoleId(Const.AgentId);
			setAttr("agents", agents);
			List<Role> roles = Role.dao.getAllList();
			setAttr("roles", roles);
		}
		if (!StrKit.isBlank(parentAgent) && !"0".equals(parentAgent)) {
			setAttr("parent_agent", parentAgent);
			sql += " and u.parent=" + parentAgent;
		}
		if (!StrKit.isBlank(searchName)) {
			setAttr("search_name", searchName);
			sql += " and u.name='" + searchName + "'";
		}
		if (searchRole != null && searchRole > 0) {
			setAttr("search_role", searchRole.toString());
			sql += " and r.id=" + searchRole.toString();
		}
		if (!StrKit.isBlank(searchDate)) {
			setAttr("search_date", searchDate);
			String[] ds = searchDate.split(" - ");
			String beginDate = ds[0] + " 00:00:00";
			String endDate = ds[1] + " 23:59:59";
			sql += " and u.createdate between '" + beginDate + "' and '" + endDate + "'";
		}
		sql = sql + " order by id desc";
		Page<UserVo> page = User.dao.customPage(pageNumber, pageSize, select, sql);
		setAttr("pageList", page);
		render("list.html");
	}

	/**
	 * 跳转到表单页面
	 */
	@RequiresPermissions(key = { "admin:sys:user:save" })
	public void add_edit() {
		Integer id = getParaToInt("id");
		User currentUser = WebUtils.currentUser(getRequest(), getResponse());
		Integer userId = currentUser.getId();
		User user = User.dao.findById(id);
		if (user != null) {
			String account = user.getAccount()==null?"":user.getAccount();
			String tmp = account.replaceAll("(\r\n|\n)", "<br>");
			user.setAccount(tmp);
			userId = id;
			setAttr("user", user);
			Role myRole = Role.dao.findRoleByUserId(id);
			setAttr("myRole", myRole);
			setAttr("agentName", Const.Agent);
		}
		List<Role> roles = Role.dao.getAllList();
		setAttr("roles", roles);
		List<User> agents = User.dao.findUserByRoleId(Const.AgentId);
		setAttr("agents", agents);
		//判断当前登录用户是管理员还是代理，跳转不同的页面
		Role role = Role.dao.findRoleByUserId(userId);
		if (Const.Administrator.equals(role.getName())) {
			render("form.html");
		} else {
			render("agent_form.html");
		}
	}

	/**
	 * 新增-更新用户
	 */
	@RequiresPermissions(key = { "admin:sys:user:save" })
	public void save_update() {
		Integer roleId = getParaToInt("role");
		User user = getModel(User.class);
		User currentUser = WebUtils.currentUser(getRequest(), getResponse());
		Role role = Role.dao.findRoleByUserId(currentUser.getId());
		if (Const.Agent.equals(role.getName())) {
			user.setParent(currentUser.getId());
			roleId = Const.CustomerId;
		}
		//user.setPwd(WebUtils.pwdEncode(user.getPwd()));
		boolean isSuccess = false;
		if (user.getId() == null) {
			user.setCreatedate(new Date());
			//判断用户是否存在
			User _user = null;
			if (Const.Agent.equals(role.getName())) {
				_user = User.dao.findFirst("select * from sys_user where name=? and parent=?", user.getName(), user.getParent());
			} else {
				_user = User.dao.findFirst("select * from sys_user where name=? ", user.getName());
			}
			if (_user != null) {
				renderJson(false, "the user has already existed");
				return;
			}
			isSuccess = user.save();
			if (isSuccess) {
				Role.dao.updateRoleByUserId(roleId, user.getId());
				renderJson(isSuccess, "added successfully");
			} else {
				renderJson(isSuccess, "failed to add");
			}
		} else {
			isSuccess = user.update();
			Role.dao.updateRoleByUserId(roleId, user.getId());
			renderJson(isSuccess, "modify successfully");
		}
	}

	/**
	 * 删除用户
	 */
	@RequiresPermissions(key = { "admin:sys:user:delete" })
	public void delete() {
		final Integer id = getParaToInt("id");
		User user = User.dao.findById(id);
		Role role = Role.dao.findRoleByUserId(user.getId());
		if (role.getId().equals(Const.AgentId)) {
			//查询代理下是否有用户，如果有不允许删除
			List<User> us = User.dao.find("select * from sys_user where parent=" + user.getId());
			if (ObjectUtils.isNotEmpty(us)) {
				renderJson(false, "此代理用户下还有子账号，请先删除子账号。");
				return;
			}
		}
		if (1 == user.getId()) {
			renderJson(false, "The superadministrator cannot delete");
		} else {
			boolean isSuccess = Db.tx(new IAtom() {
				@Override
				public boolean run() {
					try {
						UserRole.dao.deleteByUserId(id);
						Db.update("delete from sys_offer_user where user='" + id + "'");
						User.dao.deleteById(id);
						return true;
					} catch (Exception e) {
						e.printStackTrace();
						return false;
					}
				}
			});
			if (isSuccess) {
				renderJson(true, "Delete success");
			} else {
				renderJson(false, "Delete failed");
			}
		}
	}

	/**
	 * 修改用户密码跳转
	 */
	@RequiresPermissions(key = { "admin:sys:user:save" })
	public void change_password() {
		Integer id = getParaToInt("id");
		User user = User.dao.findById(id);
		setAttr("user", user);
		render("change_password.html");
	}

	/**
	 * 修改用户密码跳转
	 */
	@RequiresPermissions(key = { "admin:sys:user:save" })
	public void change_password_update() {
		Integer id = getParaToInt("id");
		String password1 = getPara("password1");
		String password2 = getPara("password2");
		if (StrKit.isBlank(password1) || StrKit.isBlank(password2) || !password1.equals(password2)) {
			renderJson(false, "Passwords that are empty or twice entered are not consistent");
		} else {
			User user = User.dao.findById(id);
			user.setPwd(WebUtils.pwdEncode(password1));
			user.update();
			renderJson(true, "Password modification successful");
		}
	}

	/**
	 * 跳转到修改自己信息表单页面
	 */
	@Clear
	public void change_info() {
		User user = WebUtils.currentUser(getRequest(), getResponse());
		user = User.dao.findById(user.getId());
		setAttr("user", user);
		render("change_info.html");
	}

	/**
	 * 修改自己信息
	 */
	@Clear
	public void change_info_update() {
		//获取当前登录用户
		User user = WebUtils.currentUser(getRequest(), getResponse());
		Integer id = user.getId();

		user = getModel(User.class);
		//设置要修改的用户ID为当前登录用户，防止通过改表单提交请求来修改其他用户信息
		user.setId(id);

		String password1 = getPara("password1");
		String password2 = getPara("password2");
		if (StrKit.notBlank(password1) && StrKit.notBlank(password2) && password1.equals(password2)) {
			if (password1.length() < 6 || password1.length() > 16) {
				renderJson(false, "The password is incorrect, with at least 6 digits up to 16 digits.");
				return;
			} else {
				user.setPwd(WebUtils.pwdEncode(password1));
			}
		}
		boolean isSuccess = user.update();
		if (isSuccess) {
			renderJson(true, "Successful information modification");
		} else {
			renderJson(false, "Information modification failed");
		}
	}

	@Clear
	public void avatar() {
		render("avatar.html");
	}

	@Clear
	public void avatar_update() {
		String para = getPara("data");
		if (StrKit.isBlank(para)) {
			renderJson(false, "请选择需要上传的头像文件");
			return;
		}
		User user = WebUtils.currentUser(getRequest(), getResponse());
		if (user == null || user.getId() == null) {
			renderJson(false, "请登录以后再尝试修改头像");
			return;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			String suffix = FileType.getSuffix("JPG");
			String[] split = para.split(",");
			byte[] bs = decoder.decodeBuffer(split[1]);
			String savePath = PathFormat.parse("/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", "upfile");
			savePath = savePath + suffix;
			State storageState = UeditorConfigKit.getFileManager().saveFile(bs, PathKit.getWebRootPath(), savePath);
			user = User.dao.findById(user.getId());
			user.setIcon(savePath);
			boolean update = user.update();
			//刷新当前登录用户的session数据，才能让修改的图片重新加载出来(注意类型key的类型必须要是long 不然无法移除)
			CacheKit.remove(Constants.CacheName.session.get(), Long.valueOf(user.getId()));
			if (update && storageState.isSuccess()) {
				renderJson(true, "修改头像成功");
			} else {
				renderJson(true, "修改头像失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(false, "文件上传出现异常" + e.getMessage());
		}
	}

}
